package com.icss.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.icss.base.logging.Log;
import com.icss.base.logging.LogFactory;
import com.icss.impl.Execute;

/**
 * Servlet implementation class TestServlet
 */

public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Log log  = LogFactory.getLog(MainServlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MainServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setHeader("Access-Control-Allow-Origin", "*");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		String inputText = request.getParameter("inputText");
		
		System.out.println("inputText:"+inputText);
		log.info("inputText:"+inputText);

		String[] cmds = { "/bin/sh", "-c", inputText };
		Process process;

		try {
			process = Runtime.getRuntime().exec(cmds);

			Execute errorGobbler = new Execute(
					process.getErrorStream(), "Error");
			Execute outputGobbler = new Execute(
					process.getInputStream(), "Output");
			errorGobbler.start();
			outputGobbler.start();
			try {
				process.waitFor();
			} catch (InterruptedException e) {
				log.info("process.waitFor()出错");
				log.info(e);
				e.printStackTrace();
			}
		} catch (IOException e) {
			log.info("process = Runtime.getRuntime().exec(cmds);方法出错");
			log.info(e);
			e.printStackTrace();
		}

		Gson gson = new Gson();

		String s = gson.toJson("访问成功");

		PrintWriter out = response.getWriter();

		out.print(s);

	}

}
